<template>
  <div class="task-management">
    <!-- 任务状态概览 -->
    <div class="task-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="status-card">
            <div class="status-content">
              <div class="status-icon running">
                <el-icon><Loading /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-value">{{ taskStats.running }}</div>
                <div class="status-label">运行中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="status-card">
            <div class="status-content">
              <div class="status-icon success">
                <el-icon><CircleCheckFilled /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-value">{{ taskStats.success }}</div>
                <div class="status-label">成功</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="status-card">
            <div class="status-content">
              <div class="status-icon failed">
                <el-icon><CircleCloseFilled /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-value">{{ taskStats.failed }}</div>
                <div class="status-label">失败</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="status-card">
            <div class="status-content">
              <div class="status-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-value">{{ taskStats.pending }}</div>
                <div class="status-label">等待中</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 任务管理标签页 -->
    <el-card style="margin-top: 20px;">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- 任务列表 -->
        <el-tab-pane label="任务列表" name="tasks">
          <div class="task-controls">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-select v-model="taskFilter.status" placeholder="任务状态" clearable>
                  <el-option label="运行中" value="PENDING" />
                  <el-option label="成功" value="SUCCESS" />
                  <el-option label="失败" value="FAILURE" />
                  <el-option label="重试" value="RETRY" />
                  <el-option label="撤销" value="REVOKED" />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-select v-model="taskFilter.task_name" placeholder="任务类型" clearable>
                  <el-option label="主机监控" value="collect_host_metrics" />
                  <el-option label="进程信息" value="collect_process_info" />
                  <el-option label="服务状态" value="check_service_status" />
                  <el-option label="连接测试" value="test_host_connectivity" />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="fetchTasks">
                  <el-icon><Search /></el-icon>
                  查询
                </el-button>
                <el-button @click="resetFilter">重置</el-button>
              </el-col>
              <el-col :span="6">
                <el-switch
                  v-model="autoRefresh"
                  active-text="自动刷新"
                  @change="toggleAutoRefresh"
                />
              </el-col>
            </el-row>
          </div>

          <el-table :data="taskList" v-loading="loading" style="margin-top: 20px;">
            <el-table-column prop="task_id" label="任务ID" width="200">
              <template #default="{ row }">
                <el-button type="text" @click="viewTaskDetail(row)">
                  {{ row.task_id.substring(0, 8) }}...
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="task_name" label="任务名称" width="150" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getTaskStatusType(row.status)">
                  {{ getTaskStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="worker" label="执行节点" width="120" />
            <el-table-column label="进度" width="120">
              <template #default="{ row }">
                <el-progress 
                  v-if="row.status === 'PENDING'"
                  :percentage="row.progress || 0"
                  :show-text="false"
                />
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="started" label="开始时间" width="160">
              <template #default="{ row }">
                {{ row.started ? formatTime(row.started) : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="runtime" label="运行时长" width="100">
              <template #default="{ row }">
                {{ row.runtime ? formatDuration(row.runtime) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button 
                  size="small" 
                  @click="viewTaskDetail(row)"
                >
                  详情
                </el-button>
                <el-button 
                  v-if="row.status === 'PENDING'"
                  size="small" 
                  type="danger"
                  @click="revokeTask(row)"
                >
                  撤销
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="taskPagination.page"
              v-model:page-size="taskPagination.size"
              :page-sizes="[10, 20, 50, 100]"
              :total="taskPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="fetchTasks"
              @current-change="fetchTasks"
            />
          </div>
        </el-tab-pane>

        <!-- 定时任务配置 -->
        <el-tab-pane label="定时任务" name="schedule">
          <div class="schedule-controls">
            <el-button type="primary" @click="showScheduleDialog = true">
              <el-icon><Plus /></el-icon>
              添加定时任务
            </el-button>
          </div>

          <el-table :data="scheduleList" style="margin-top: 20px;">
            <el-table-column prop="name" label="任务名称" width="200" />
            <el-table-column prop="task" label="任务类型" width="150" />
            <el-table-column prop="schedule" label="执行计划" width="150" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-switch 
                  v-model="row.enabled" 
                  @change="toggleSchedule(row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="last_run_at" label="上次执行" width="160">
              <template #default="{ row }">
                {{ row.last_run_at ? formatTime(row.last_run_at) : '从未执行' }}
              </template>
            </el-table-column>
            <el-table-column prop="total_run_count" label="执行次数" width="100" />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button size="small" @click="editSchedule(row)">
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  type="danger"
                  @click="deleteSchedule(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 工作节点 -->
        <el-tab-pane label="工作节点" name="workers">
          <div class="worker-controls">
            <el-button @click="fetchWorkers">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>

          <el-table :data="workerList" style="margin-top: 20px;">
            <el-table-column prop="name" label="节点名称" width="200" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.online ? 'success' : 'danger'">
                  {{ row.online ? '在线' : '离线' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="active" label="活跃任务" width="100" />
            <el-table-column prop="processed" label="已处理" width="100" />
            <el-table-column prop="load" label="负载" width="100">
              <template #default="{ row }">
                {{ (row.load * 100).toFixed(1) }}%
              </template>
            </el-table-column>
            <el-table-column prop="last_heartbeat" label="最后心跳" width="160">
              <template #default="{ row }">
                {{ formatTime(row.last_heartbeat) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button size="small" @click="viewWorkerDetail(row)">
                  详情
                </el-button>
                <el-button 
                  v-if="row.online"
                  size="small" 
                  type="warning"
                  @click="shutdownWorker(row)"
                >
                  关闭
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 任务详情对话框 -->
    <el-dialog
      v-model="showTaskDialog"
      title="任务详情"
      width="70%"
      :close-on-click-modal="false"
    >
      <div v-if="selectedTask" class="task-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="任务ID">
            {{ selectedTask.task_id }}
          </el-descriptions-item>
          <el-descriptions-item label="任务名称">
            {{ selectedTask.task_name }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getTaskStatusType(selectedTask.status)">
              {{ getTaskStatusText(selectedTask.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行节点">
            {{ selectedTask.worker }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ selectedTask.started ? formatTime(selectedTask.started) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="运行时长">
            {{ selectedTask.runtime ? formatDuration(selectedTask.runtime) : '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="selectedTask.args" style="margin-top: 20px;">
          <h4>任务参数：</h4>
          <pre class="task-args">{{ JSON.stringify(selectedTask.args, null, 2) }}</pre>
        </div>

        <div v-if="selectedTask.result" style="margin-top: 20px;">
          <h4>执行结果：</h4>
          <pre class="task-result">{{ JSON.stringify(selectedTask.result, null, 2) }}</pre>
        </div>

        <div v-if="selectedTask.traceback" style="margin-top: 20px;">
          <h4>错误信息：</h4>
          <pre class="task-error">{{ selectedTask.traceback }}</pre>
        </div>
      </div>
    </el-dialog>

    <!-- 定时任务配置对话框 -->
    <el-dialog
      v-model="showScheduleDialog"
      title="定时任务配置"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="scheduleForm" label-width="100px">
        <el-form-item label="任务名称" required>
          <el-input v-model="scheduleForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型" required>
          <el-select v-model="scheduleForm.task" placeholder="请选择任务类型">
            <el-option label="主机监控" value="collect_host_metrics" />
            <el-option label="进程信息" value="collect_process_info" />
            <el-option label="服务状态" value="check_service_status" />
            <el-option label="数据清理" value="cleanup_old_metrics" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行计划" required>
          <el-input 
            v-model="scheduleForm.crontab" 
            placeholder="Cron表达式，如: 0 */5 * * *"
          />
          <div class="cron-help">
            <small>格式：分 时 日 月 周，例如：0 */5 * * * 表示每5分钟执行一次</small>
          </div>
        </el-form-item>
        <el-form-item label="任务参数">
          <el-input 
            v-model="scheduleForm.kwargs" 
            type="textarea" 
            placeholder="JSON格式的任务参数"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch v-model="scheduleForm.enabled" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showScheduleDialog = false">取消</el-button>
        <el-button type="primary" @click="saveSchedule">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Loading, CircleCheckFilled, CircleCloseFilled, Clock, Search, 
  Plus, Refresh
} from '@element-plus/icons-vue'
import api from '@/utils/api'

// 响应式数据
const activeTab = ref('tasks')
const loading = ref(false)
const autoRefresh = ref(false)
let refreshInterval: number | null = null

// 任务统计
const taskStats = reactive({
  running: 0,
  success: 0,
  failed: 0,
  pending: 0
})

// 任务列表
const taskList = ref([])
const taskFilter = reactive({
  status: '',
  task_name: ''
})
const taskPagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 定时任务
const scheduleList = ref([])
const showScheduleDialog = ref(false)
const scheduleForm = reactive({
  name: '',
  task: '',
  crontab: '',
  kwargs: '',
  enabled: true
})

// 工作节点
const workerList = ref([])

// 任务详情
const showTaskDialog = ref(false)
const selectedTask = ref(null)

// 获取任务统计
const fetchTaskStats = async () => {
  try {
    const response = await api.get('/monitoring/tasks/stats/')
    if (response.data.success) {
      Object.assign(taskStats, response.data.data)
    }
  } catch (error) {
    console.error('获取任务统计失败:', error)
  }
}

// 获取任务列表
const fetchTasks = async () => {
  try {
    loading.value = true
    const params = {
      page: taskPagination.page,
      page_size: taskPagination.size,
      ...taskFilter
    }
    
    const response = await api.get('/monitoring/tasks/', { params })
    if (response.data.success) {
      taskList.value = response.data.data.results
      taskPagination.total = response.data.data.count
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取定时任务
const fetchSchedules = async () => {
  try {
    const response = await api.get('/monitoring/schedules/')
    if (response.data.success) {
      scheduleList.value = response.data.data
    }
  } catch (error) {
    console.error('获取定时任务失败:', error)
  }
}

// 获取工作节点
const fetchWorkers = async () => {
  try {
    const response = await api.get('/monitoring/workers/')
    if (response.data.success) {
      workerList.value = response.data.data
    }
  } catch (error) {
    console.error('获取工作节点失败:', error)
  }
}

// 工具函数
const getTaskStatusType = (status: string) => {
  const typeMap = {
    'PENDING': 'warning',
    'SUCCESS': 'success',
    'FAILURE': 'danger',
    'RETRY': 'info',
    'REVOKED': 'info'
  }
  return typeMap[status] || 'info'
}

const getTaskStatusText = (status: string) => {
  const textMap = {
    'PENDING': '运行中',
    'SUCCESS': '成功',
    'FAILURE': '失败',
    'RETRY': '重试',
    'REVOKED': '撤销'
  }
  return textMap[status] || status
}

const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

const formatDuration = (seconds: number) => {
  if (seconds < 60) {
    return `${seconds.toFixed(1)}s`
  } else if (seconds < 3600) {
    return `${(seconds / 60).toFixed(1)}m`
  } else {
    return `${(seconds / 3600).toFixed(1)}h`
  }
}

// 事件处理
const handleTabClick = (tab: any) => {
  if (tab.name === 'schedule') {
    fetchSchedules()
  } else if (tab.name === 'workers') {
    fetchWorkers()
  }
}

const resetFilter = () => {
  Object.assign(taskFilter, {
    status: '',
    task_name: ''
  })
  fetchTasks()
}

const toggleAutoRefresh = (enabled: boolean) => {
  if (enabled) {
    refreshInterval = setInterval(() => {
      fetchTaskStats()
      if (activeTab.value === 'tasks') {
        fetchTasks()
      }
    }, 5000)
  } else {
    if (refreshInterval) {
      clearInterval(refreshInterval)
      refreshInterval = null
    }
  }
}

const viewTaskDetail = (task: any) => {
  selectedTask.value = task
  showTaskDialog.value = true
}

const revokeTask = async (task: any) => {
  try {
    await ElMessageBox.confirm('确定要撤销这个任务吗？', '撤销确认')
    
    const response = await api.post(`/monitoring/tasks/${task.task_id}/revoke/`)
    if (response.data.success) {
      ElMessage.success('任务撤销成功')
      fetchTasks()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('任务撤销失败')
    }
  }
}

const saveSchedule = async () => {
  try {
    const data = { ...scheduleForm }
    if (data.kwargs) {
      try {
        data.kwargs = JSON.parse(data.kwargs)
      } catch {
        ElMessage.error('任务参数格式错误，请输入有效的JSON')
        return
      }
    }
    
    const response = await api.post('/monitoring/schedules/', data)
    if (response.data.success) {
      ElMessage.success('定时任务保存成功')
      showScheduleDialog.value = false
      fetchSchedules()
    }
  } catch (error) {
    ElMessage.error('定时任务保存失败')
  }
}

const toggleSchedule = async (schedule: any) => {
  try {
    const response = await api.put(`/monitoring/schedules/${schedule.id}/`, {
      enabled: schedule.enabled
    })
    if (response.data.success) {
      ElMessage.success(`定时任务已${schedule.enabled ? '启用' : '禁用'}`)
    }
  } catch (error) {
    ElMessage.error('操作失败')
    schedule.enabled = !schedule.enabled // 回滚状态
  }
}

const editSchedule = (schedule: any) => {
  Object.assign(scheduleForm, schedule)
  showScheduleDialog.value = true
}

const deleteSchedule = async (schedule: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个定时任务吗？', '删除确认')
    
    const response = await api.delete(`/monitoring/schedules/${schedule.id}/`)
    if (response.data.success) {
      ElMessage.success('定时任务删除成功')
      fetchSchedules()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('定时任务删除失败')
    }
  }
}

const viewWorkerDetail = (worker: any) => {
  ElMessage.info('工作节点详情功能开发中')
}

const shutdownWorker = async (worker: any) => {
  try {
    await ElMessageBox.confirm('确定要关闭这个工作节点吗？', '关闭确认')
    
    const response = await api.post(`/monitoring/workers/${worker.name}/shutdown/`)
    if (response.data.success) {
      ElMessage.success('工作节点关闭成功')
      fetchWorkers()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('工作节点关闭失败')
    }
  }
}

// 生命周期
onMounted(() => {
  fetchTaskStats()
  fetchTasks()
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<style scoped>
.task-management {
  padding: 20px;
}

.task-overview {
  margin-bottom: 20px;
}

.status-card {
  border-radius: 8px;
  overflow: hidden;
}

.status-content {
  display: flex;
  align-items: center;
  padding: 15px;
}

.status-icon {
  font-size: 32px;
  margin-right: 15px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-icon.running {
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
  animation: spin 2s linear infinite;
}

.status-icon.success {
  background: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.status-icon.failed {
  background: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.status-icon.pending {
  background: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.status-info .status-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.status-info .status-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.task-controls,
.schedule-controls,
.worker-controls {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.task-detail {
  padding: 20px 0;
}

.task-args,
.task-result,
.task-error {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.task-error {
  background: #fef0f0;
  color: #f56c6c;
}

.cron-help {
  margin-top: 5px;
  color: #909399;
}
</style>
